﻿using System.Security.Principal;
using ServiceClient.UserService;

namespace ServiceClient
{
    public class UserServiceClient
    {
        private const long LanguageId = 8;
        private readonly UserServicePortTypeClient _serviceClient;

        public UserServiceClient()
        {
            _serviceClient = new UserServicePortTypeClient();
        }

        public string GetNewToken()
        {
            var data = _serviceClient.getSession();
            return data.session_id;
        }

        public bool Login(string user, string pass, string token, out string errorMsg)
        {
            var result = _serviceClient.loginUser(token, user, pass);

            errorMsg = string.Empty;

            if (result == 1)
                return true;

            // Error
            errorMsg = GetErrorMessage(token, result);
            return false;
        }

        private string GetErrorMessage(string token, long errorCode)
        {
            var err = _serviceClient.getErrorByCode(token, errorCode, LanguageId);

            return err == null
                ? "No se pudo obtener el mensaje de error."
                : string.Format("{0}: {1}.", err.errortype, err.errmessage);
        }
    }
}
